import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { nanoid } from "nanoid";
import axios from "axios";

// 调用createAsyncThunk实现一个异步动作
//      有三个状态 Promise
//        1. pending
//        2. fulfilled
//        3. rejected
export const loadData = createAsyncThunk("loadData", async () => {
  const response = await axios.get("http://localhost:5000/todos");
  return response.data;
});

const todosSlice = createSlice({
  name: "todos",
  initialState: [],
  reducers: {
    add(state, { payload }) {
      state.push({
        id: nanoid(),
        text: payload,
        done: false,
      });
    },
    toggle(state, { payload }) {
      // id
      const todo = state.find((item) => item.id === payload);
      todo.done = !todo.done;
    },
  },
  extraReducers: {
    [loadData.pending](state) {
      console.log("loadData pending");
      // 处理一下要不要转圈
    },
    [loadData.fulfilled](state, { payload }) {
      console.log("loadData fulfilled", payload);
      // 处理数据, 如果是重新赋值的话，需要return
      return (state = payload);
    },
    [loadData.rejected](state) {
      console.log("loadData rejected");
    },
  },
});

export const { add, toggle } = todosSlice.actions;

export default todosSlice.reducer;
